package com.sync;

/**
 * 脏读
 * 学习点01
 * 与锁对象相同
 * 同样对象 setValue方法加上锁 get没加锁
 * 在访问过程中 如果在set过程中, 其他线程访问 get方法 则get方法会取到当前设置的值 造成脏读
 * 解决方法为 set 和 get方法 同时 具有对象锁
 *
 * @author bysun
 */
class PublicVar {
    public String username = "A";
    public String password = "AA";

    synchronized public void setValue(String username, String password) {
        try {
            this.username = username;
            Thread.sleep(5000);
            this.password = password;
            System.out.println("setValue ThreadName = " + Thread.currentThread().getName() +
                    ", username = " + username + " password = " + password);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    synchronized public void getValue() {
        System.out.println("getValue ThreadName = " + Thread.currentThread().getName() +
                ", username = " + username + " password = " + password);
    }
}

class ThreadG extends Thread {
    private PublicVar publicVar;

    public ThreadG(PublicVar publicVar) {
        this.publicVar = publicVar;
    }

    @Override
    public void run() {
        super.run();
        publicVar.setValue("B", "BB");
    }
}

/**
 * @author bysun
 */
public class Demo04 {
    public static void main(String[] args) {
        try {
            PublicVar publicVar = new PublicVar();
            ThreadG threadG = new ThreadG(publicVar);
            threadG.setName("G");
            threadG.start();
            Thread.sleep(3000);
            publicVar.getValue();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
